package com.jews.framework.json;

import com.jews.framework.json.jackson.CustomizeJacksonJSONBuilder;
import com.jn.easyjson.core.JSON;
import lombok.Getter;

/**
 * @author Bran Wang
 */
public class JsonUtils extends AbstractJsonUtils {

    private volatile static JsonUtils instance = null;

    @Getter
    private final JSON json;

    private JsonUtils() {
        this.json = new CustomizeJacksonJSONBuilder().build();
    }

    /**
     * 双重检查加锁机制单例模式
     */
    public static JsonUtils getInstance() {
        if (instance == null) {
            synchronized (JsonUtils.class) {
                if (instance == null) {
                    instance = new JsonUtils();
                }
            }
        }
        return instance;
    }

    public static JsonUtils getSerializeNullsInstance() {
        return JsonSerializeNullsUtils.getInstance();
    }

    /**
     * 空字段也参与序列化的相关配置
     * <p>
     * 用于网络传输中序列化空参数丢失字段的情况
     */
    static class JsonSerializeNullsUtils extends JsonUtils {

        private volatile static JsonSerializeNullsUtils instance = null;

        @Getter
        private final JSON json;

        private JsonSerializeNullsUtils() {
            this.json = new CustomizeJacksonJSONBuilder()
                    // 空字段也参与序列化的相关配置
                    .serializeNulls(true)
                    .build();
        }

        /**
         * 双重检查加锁机制单例模式
         */
        public static JsonSerializeNullsUtils getInstance() {
            if (instance == null) {
                synchronized (JsonSerializeNullsUtils.class) {
                    if (instance == null) {
                        instance = new JsonSerializeNullsUtils();
                    }
                }
            }
            return instance;
        }
    }
}
